import axios from 'axios'

function Axios({ baseURL, headers = {}}) {
  this.baseURL = baseURL
  this.headers = headers
  this.instance = axios.create()
  this.interceptors(this.instance)
}

// 获取实例配置
Axios.prototype.request = function(options) {
  options = Object.assign(this.getInsideConfig(), options)
  return this.instance.request(options)
}

// get方法
Axios.prototype.get = function(url, data, config) {
  return this.request({
    url,
    method: 'get',
    params: data,
    ...config
  })
}

// post方法
Axios.prototype.post = function(url, data, config = {}) {
  return this.request({
    url,
    method: 'post',
    data,
    ...config
  })
}

// put方法
Axios.prototype.put = function(url, data, config = {}) {
  return this.request({
    url,
    method: 'put',
    data,
    ...config
  })
}

// delete方法
Axios.prototype.delete = function(url, data, config = {}) {
  return this.request({
    url,
    method: 'delete',
    data,
    ...config
  })
}

// 获取实例配置
Axios.prototype.getInsideConfig = function() {
  return {
    baseURL: this.baseURL,
    headers: this.headers,
  }
}

// 接口拦截
Axios.prototype.interceptors = function(instance) {
  // 请求拦截
  instance.interceptors.request.use(
    config => {
      return config
    },
    error => {
      // do something with request error
      return Promise.reject(error)
    }
  )
  // 响应拦截
  instance.interceptors.response.use(
    response => {
      return response
    },
    error => {
      return Promise.reject(error)
    }
  )
}

export default Axios

